<template>
  <div class="browser-container">
    <!-- 导航控制栏 -->
    <div class="navigation-bar">
      <div class="nav-controls">
        <button @click="goBack" :disabled="!canGoBack" title="后退">
          ←
        </button>
        <button @click="goForward" :disabled="!canGoForward" title="前进">
          →
        </button>
        <button @click="reload" title="刷新">
          ↻
        </button>
        <button @click="goHome" title="主页">
          🏠
        </button>
      </div>

      <!-- 地址和搜索栏 -->
      <div class="address-bar">
        <input
          type="text"
          v-model="currentInputUrl"
          @keyup.enter="navigateToInput"
          @focus="showSuggestions = true"
          @blur="onAddressBlur"
          placeholder="输入网址或搜索内容..."
          ref="addressInput"
        />
        <button @click="navigateToInput" title="前往">
          →
        </button>
        
        <!-- 搜索建议（可选） -->
        <div v-if="showSuggestions && currentInputUrl" class="suggestions">
          <div 
            v-for="suggestion in getSearchSuggestions()" 
            :key="suggestion"
            @mousedown="selectSuggestion(suggestion)"
            class="suggestion-item"
          >
            {{ suggestion }}
          </div>
        </div>
      </div>

      <!-- 更多功能 -->
      <div class="additional-controls">
        <button @click="openDevTools" title="开发者工具">
          🔧
        </button>
        <button @click="zoomIn" title="放大">
          +
        </button>
        <button @click="zoomOut" title="缩小">
          -
        </button>
        <button @click="resetZoom" title="重置缩放">
          100%
        </button>
      </div>
    </div>

    <!-- 加载进度条 -->
    <div v-if="isLoading" class="progress-bar">
      <div class="progress" :style="{ width: loadProgress + '%' }"></div>
    </div>

    <!-- 网页内容区域 -->
    <webview
      ref="webviewRef"
      :src="currentUrl"
      class="webview-content"
      :allowpopups="true"
      @did-start-loading="onLoadStart"
      @did-stop-loading="onLoadEnd"
      @did-finish-load="onLoadFinish"
      @did-fail-load="onLoadError"
      @page-title-updated="updateTitle"
      @did-navigate="updateNavigationState"
      @did-navigate-in-page="updateNavigationState"
      @new-window="onNewWindow"
    ></webview>

    <!-- 状态栏 -->
    <div class="status-bar">
      <span v-if="isLoading">加载中... {{ loadProgress }}%</span>
      <span v-else-if="loadError">加载失败: {{ loadError }}</span>
      <span v-else>{{ statusText }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';

const webviewRef = ref(null);
const currentUrl = ref('https://www.baidu.com'); // 默认主页
const currentInputUrl = ref('');
const canGoBack = ref(false);
const canGoForward = ref(false);
const isLoading = ref(false);
const loadProgress = ref(0);
const loadError = ref(null);
const showSuggestions = ref(false);
const statusText = ref('就绪');
const zoomLevel = ref(0);

// 搜索引擎配置
const searchEngines = {
  baidu: 'https://www.baidu.com/s?wd=',
  google: 'https://www.google.com/search?q=',
  bing: 'https://www.bing.com/search?q='
};
const defaultSearchEngine = 'baidu';

onMounted(async () => {
  await nextTick(); // 等待DOM更新
  const webview = webviewRef.value;
  
  if (webview) {
    webview.addEventListener('dom-ready', () => {
      console.log('Webview准备就绪');
      // 注入自定义样式或脚本
      webview.insertCSS(`
        /* 可以在这里修改嵌入页面的样式 */
      `);
    });

    webview.addEventListener('did-change-theme-color', (event) => {
      // 可以根据网页主题色调整UI
      console.log('主题色变化:', event.themeColor);
    });
  }
});

// 导航方法
const navigateTo = (url) => {
  if (!url) return;
  
  let finalUrl = url;
  // 如果不是完整的URL，认为是搜索词
  if (!url.includes('://') && !url.startsWith('about:') && !url.startsWith('file://')) {
    if (url.includes('.') && !url.includes(' ')) {
      // 看起来像域名，尝试添加https://
      finalUrl = 'https://' + url;
    } else {
      // 认为是搜索词
      finalUrl = `${searchEngines[defaultSearchEngine]}${encodeURIComponent(url)}`;
    }
  }
  
  currentUrl.value = finalUrl;
  currentInputUrl.value = finalUrl;
  loadError.value = null;
  showSuggestions.value = false;
};

const navigateToInput = () => {
  navigateTo(currentInputUrl.value);
};

const goBack = () => {
  if (webviewRef.value && canGoBack.value) {
    webviewRef.value.goBack();
  }
};

const goForward = () => {
  if (webviewRef.value && canGoForward.value) {
    webviewRef.value.goForward();
  }
};

const reload = () => {
  if (webviewRef.value) {
    webviewRef.value.reload();
  }
};

const goHome = () => {
  navigateTo('https://www.baidu.com');
};

// Webview事件处理
const onLoadStart = () => {
  isLoading.value = true;
  loadProgress.value = 0;
  statusText.value = '开始加载...';
};

const onLoadEnd = () => {
  isLoading.value = false;
  loadProgress.value = 100;
};

const onLoadFinish = (event) => {
  statusText.value = '加载完成';
  if (webviewRef.value) {
    currentInputUrl.value = webviewRef.value.getURL();
  }
};

const onLoadError = (event) => {
  loadError.value = `错误代码: ${event.errorCode}, ${event.errorDescription}`;
  statusText.value = '加载失败';
};

const updateTitle = (event) => {
  document.title = `${event.title} - 我的浏览器`;
};

const updateNavigationState = () => {
  if (webviewRef.value) {
    canGoBack.value = webviewRef.value.canGoBack();
    canGoForward.value = webviewRef.value.canGoForward();
    currentInputUrl.value = webviewRef.value.getURL();
  }
};

// 开发者工具和缩放
const openDevTools = () => {
  if (webviewRef.value) {
    webviewRef.value.openDevTools();
  }
};

const zoomIn = () => {
  if (webviewRef.value) {
    zoomLevel.value += 0.1;
    webviewRef.value.setZoomLevel(zoomLevel.value);
  }
};

const zoomOut = () => {
  if (webviewRef.value) {
    zoomLevel.value -= 0.1;
    webviewRef.value.setZoomLevel(zoomLevel.value);
  }
};

const resetZoom = () => {
  if (webviewRef.value) {
    zoomLevel.value = 0;
    webviewRef.value.setZoomLevel(0);
  }
};

// 搜索建议功能
const getSearchSuggestions = () => {
  const input = currentInputUrl.value.toLowerCase();
  if (input.length < 2) return [];
  
  const suggestions = [
    `${searchEngines.baidu}${input}`,
    `${searchEngines.google}${input}`,
    `${searchEngines.bing}${input}`,
    `https://www.${input}.com`,
    `https://${input}.com`
  ];
  
  return suggestions.filter((s, i) => suggestions.indexOf(s) === i);
};

const selectSuggestion = (suggestion) => {
  currentInputUrl.value = suggestion;
  showSuggestions.value = false;
  navigateToInput();
};

const onAddressBlur = () => {
  setTimeout(() => {
    showSuggestions.value = false;
  }, 200);
};

// 处理新窗口打开请求
const onNewWindow = (event) => {
  event.preventDefault();
  navigateTo(event.url);
};

// 将handleKeydown移到外部作用域
const handleKeydown = (event) => {
  if (event.ctrlKey || event.metaKey) {
    switch (event.key) {
      case 'r':
        event.preventDefault();
        reload();
        break;
      case 'l':
        event.preventDefault();
        document.querySelector('.address-bar input').focus();
        break;
      case 't':
        event.preventDefault();
        // 这里可以实现新建标签页功能
        break;
    }
  }
};

onMounted(async () => {
  await nextTick(); // 等待DOM更新
  const webview = webviewRef.value;
  
  if (webview) {
    webview.addEventListener('dom-ready', () => {
      console.log('Webview准备就绪');
      // 注入自定义样式或脚本
      webview.insertCSS(`
        /* 可以在这里修改嵌入页面的样式 */
      `);
    });

    webview.addEventListener('did-change-theme-color', (event) => {
      // 可以根据网页主题色调整UI
      console.log('主题色变化:', event.themeColor);
    });
  }
  
  // 添加键盘事件监听器
  window.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  // 移除键盘事件监听器
  window.removeEventListener('keydown', handleKeydown);
});
</script>

<style scoped>
.browser-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.navigation-bar {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #fff;
  border-bottom: 1px solid #e0e0e0;
  gap: 10px;
}

.nav-controls, .additional-controls {
  display: flex;
  gap: 5px;
}

.nav-controls button, .additional-controls button {
  padding: 6px 10px;
  border: 1px solid #ddd;
  background: #f8f8f8;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.nav-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.nav-controls button:hover:not(:disabled) {
  background: #e8e8e8;
}

.address-bar {
  flex: 1;
  position: relative;
  display: flex;
}

.address-bar input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
  font-size: 14px;
}

.address-bar input:focus {
  border-color: #4285f4;
}

.address-bar button {
  margin-left: 5px;
  padding: 8px 12px;
  border: none;
  background: #4285f4;
  color: white;
  border-radius: 20px;
  cursor: pointer;
}

.suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 4px 4px;
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.suggestion-item:hover {
  background: #f0f0f0;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.progress-bar {
  height: 3px;
  background: #e0e0e0;
  width: 100%;
}

.progress {
  height: 100%;
  background: #4285f4;
  transition: width 0.3s ease;
}

.webview-content {
  flex: 1;
  width: 100%;
  border: none;
}

.status-bar {
  padding: 4px 12px;
  background: #f8f8f8;
  border-top: 1px solid #e0e0e0;
  font-size: 12px;
  color: #666;
}
</style>